package ink.tiptop.configuration;

import ink.tiptop.common.cache.ICache;
import ink.tiptop.common.ContextHolder;
import ink.tiptop.constant.AuthConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ink.tiptop.zjf
 * @Title: Ticket
 * @Package ink.tiptop.common.interceptor
 * @Description: 自定义登陆拦截器
 * @date 2020-06-25 21:58
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Autowired
    private ICache cache;

    private boolean isResource(String url) {
        for (String suffix : AuthConst.RESOURCE) {
            if (url.endsWith(suffix)) {
                return true;
            }
        }
        return false;
    }

    public boolean go(HttpServletRequest request) {
        String requestUri = request.getRequestURI().trim();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        // 修复这个bug
        // /assets/js/home/home.js;jsessionid=07D51E501680DD67AD2CA880A6961A04
        int idx = url.indexOf(";jsessionid=");
        if (idx > -1) {
            url = url.substring(0, url.indexOf(";jsessionid="));
        }
        return AuthConst.PATH_FREE.contains(url) || isResource(url);
//        return AuthConst.PATH_FREE.contains(url);
    }

    /**
     * 在业务处理器处理请求之前被调用
     * 如果返回false
     * 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
     * <p>
     * 如果返回true
     * 执行下一个拦截器,直到所有的拦截器都执行完毕
     * 再执行被拦截的Controller
     * 然后进入拦截器链,
     * 从最后一个拦截器往回执行所有的postHandle()
     * 接着再从最后一个拦截器往回执行所有的afterCompletion()
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 添加本地线程拷贝参数对象
        ContextHolder.setLocalRequest(request);
        ContextHolder.setLocalResponse(response);

        // 登录页面 登录接口 资源路径 不需要拦截
        if (go(request)) {
            return true;
        }
        // 获取不到的时候 就创建一个session
        HttpSession session = request.getSession(true);
        // 获取sessionId 这里如果有缓存 说明已经登录过了
        Object sessionId = session.getAttribute(AuthConst.SESSION_ID);
        // 是否失效
        Object val = cache.getVal(AuthConst.SESSION_ID, AuthConst.CACHE_TYPE);

        if (sessionId != null && val != null) {
            return true;
        }
        log.info("Interceptor：跳转到login页面！");

        // 让thymeleaf去跳转
        request.getRequestDispatcher("/login").forward(request, response);

        return false;
    }

    /**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
     * 可在modelAndView中加入数据，比如当前时间
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {  //加入当前时间
            modelAndView.addObject("haha", "测试postHandle");
        }

    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
